const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackBar = require('webpackbar'); // 打包进度条美化
const [
    SRC_PATH,
    DIST_PATH,
    IS_DEV,
    ROOT_PATH,
] = [
    path.resolve(__dirname, '../', 'src'),
    path.resolve(__dirname, '../', 'dist'),
    (process.env.NODE_ENV || 'dev') === 'dev',
    path.resolve(__dirname, '../'),
];
const config = {
    entry: {
        index: path.join(SRC_PATH, 'index.tsx'),
    },
    output: {
        path: DIST_PATH,
        filename: IS_DEV ? 'js/[name].bundle.js' : 'js/[name].[contenthash:8].bundle.js',
        publicPath: '/',
        globalObject: 'this',
        chunkFilename: IS_DEV ? 'js/[name].chunk.js' : 'js/[name].[contenthash:8].chunk.js',
        assetModuleFilename: 'assets/[hash][ext][query]',
        clean: true, // 在生成文件之前清空 output 目录
    },
    performance: {
        hints: false,
    },
    module: {
        rules: [
            {
                test: /\.(tsx?|ts)$/,
                include: [SRC_PATH],
                use: [
                    // 使用esbuild-loader 替代 babel-loader
                    {
                        loader: 'esbuild-loader',
                        options: {
                            loader: 'tsx',
                            target: 'es2015',
                        },
                    },
                ],
                // use: [
                //     // 开启多进程打包
                //     {
                //         loader: 'thread-loader',
                //         options: {
                //             workers: require('os').cpus().length * 2,
                //             parallel: true,
                //             workerParallelJobs: 50,
                //         },
                //     },
                //     {
                //         loader: 'babel-loader', // 这是一个webpack优化点，使用缓存
                //         options: {
                //             cacheDirectory: true,
                //         },
                //     },
                // ],
            },
            // css/less 文件
            {
                test: /\.(c|le)ss$/,
                use: [
                    IS_DEV ? 'style-loader' : MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                    }, {
                        loader: 'esbuild-loader',
                        options: {
                            loader: 'css',
                            minify: true,
                        },
                    }, {
                        loader: "postcss-loader",
                        options: {
                            postcssOptions: {
                                plugins: [["postcss-preset-env"]],
                            },
                        },
                    }, {
                        loader: 'less-loader',
                        options: {
                            lessOptions: {
                                modifyVars: {
                                    'primary-color': 'rgb(24, 144, 255)',
                                    'link-color': 'rgb(210, 12, 17)',
                                },
                                javascriptEnabled: true,
                            },
                        },
                    },
                    {
                        loader: 'style-resources-loader',
                        options: {
                            patterns: [path.resolve(__dirname, '../src/assets/css/core.less')],
                        },
                    },
                ].filter(Boolean),
            },
            {
                test: /\.(png|jpg|gif|jpeg|webp|svg)$/,
                type: 'asset/resource',
                generator: {
                    filename: 'assets/images/[contenthash][ext][query]',
                },
            },
            // 字体图标
            // {
            //     test: /\.(woff|woff2|eot|ttf|otf)$/i,
            //     type: 'asset/resource',
            //     generator: {
            //         filename: 'assets/fonts/[contenthash][ext][query]',
            //     },
            // },
        ],
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js', '.json'],
        modules: [path.resolve(ROOT_PATH, 'node_modules')],
        mainFields: ['browser', 'module', 'main'],
        alias: {
            '@': SRC_PATH,
            '@images': path.resolve(SRC_PATH, 'assets/images'),
        },
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(path.resolve(__dirname, '../', 'public'), 'index.html'),
            filename: 'index.html',
            inject: true, //true 插入body底部，head:插入head标签，false:不生成js文件
            hash: true, // 会在打包好的bundle.js后面加上hash串
            title: 'react',
            minify: {
                removeComments: true, // 删除注释
                collapseWhitespace: false, // 折叠空格
                removeRedundantAttributes: true, // 删除多余（默认）属性
                removeEmptyAttributes: true,  // 删除空属性
                minifyCSS: true, // 压缩 HTML 中出现的 CSS 代码
                minifyJS: true, // 压缩 HTML 中出现的 JS 代码
            },
        }),
        new MiniCssExtractPlugin({
            filename: 'css/[fullhash].[name].css',
            chunkFilename: 'css/[fullhash].[id].css',
            ignoreOrder: false,
        }),
        new WebpackBar(),
    ],
};

module.exports = config;
